const std = @import("std");

const c = @cImport({
    @cInclude("SDL.h");
    @cInclude("SDL_mixer.h");
});

pub fn main() !void {
    const allocator = std.heap.page_allocator;

    const args = try std.process.argsAlloc(allocator);
    defer std.process.argsFree(allocator, args);

    if (args.len != 3) {
        std.log.err("Usage: {s} <bpm <accent_every_n_beats>", .{std.os.argv[0]});
        return error.InvalidArguments;
    }
    const toneDuration = 100;
    const bpm = try std.fmt.parseInt(u32, args[1], 10);
    const accent_every_n_beats = try std.fmt.parseInt(u32, args[2], 10);

    if ((c.SDL_Init(c.SDL_INIT_AUDIO) < 0) or (c.Mix_OpenAudio(44100, c.MIX_DEFAULT_FORMAT, 2, 2048) < 0)) {
        std.log.err("SDL_Init failed: {s}", .{c.SDL_GetError()});
        return error.SDLInitFailed;
    }
    defer c.Mix_CloseAudio();
    defer c.SDL_Quit();

    // load audio file tone440.wav
    const tone440 = c.Mix_LoadWAV("tone440.wav");
    if (tone440 == null) {
        std.log.err("Mix_LoadWAV failed: {s}", .{c.SDL_GetError()});
        return error.LoadAudioFailed;
    }
    defer c.Mix_FreeChunk(tone440);

    const tone880 = c.Mix_LoadWAV("tone880.wav");
    if (tone880 == null) {
        std.log.err("Mix_LoadWAV failed: {s}", .{c.SDL_GetError()});
        return error.LoadAudioFailed;
    }
    defer c.Mix_FreeChunk(tone880);

    const beatInterval = 60 * 1000 / bpm;
    var i: u32 = 0;
    while (true) : (i += 1) {
        if (i % accent_every_n_beats == 0) {
            _ = c.Mix_PlayChannelTimed(-1, tone880, 0, toneDuration);
        } else {
            _ = c.Mix_PlayChannelTimed(-1, tone440, 0, toneDuration);
        }
        c.SDL_Delay(beatInterval);
        var e: c.SDL_Event = undefined;
        while (c.SDL_PollEvent(&e) != 0) {
            switch (e.type) {
                c.SDL_QUIT => return,
                else => {},
            }
        }
    }
}
